//
//  ViewController.m
//  MAC服务器Socket
//
//  Created by 叶文凯 on 16/12/6.
//  Copyright © 2016年 葱花思鸡蛋. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"

@interface ViewController ()<GCDAsyncSocketDelegate>
//服务器端用于监听的socket
@property(nonatomic,strong)GCDAsyncSocket * listenSocket;
//用于保存链接到服务器的客户端开启的端口 保证newSocket是强引用
@property(nonatomic,strong)NSMutableArray<GCDAsyncSocket *> *connectSockets;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}
//点击开启服务器
- (IBAction)startSever:(id)sender {
    
   BOOL isSuccess = [self.listenSocket acceptOnInterface:@"127.0.0.1" port:1234 error:nil];
    
    if (isSuccess) {
        NSLog(@"服务器开启成功");
    }else
    {
        NSLog(@"服务器开启失败");
    }
    
}
#pragma mark - GCDAsyncSocketDelegate
//客户端已经连接服务器后调用
//可以使用终端进行客服端测试 telnet ip地址 端口号/  telnet 127.0.0.1 1234
// newSocket 必须强引用，不然连接后会立即断开
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    NSLog(@"客服端链接到服务器");
    [self.connectSockets addObject:newSocket];
    NSString *str = @"欢迎连接到服务器";
    // 向客户端发送数据
    [newSocket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    // 接收客服端发送的消息 不调用此方法无法接收到客服端发送的数据下面的代理方法不会被调用
    [newSocket readDataWithTimeout:-1 tag:0];
}
// 服务器接收到客服端的数据
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    // 接收到消息后，再次调用此方法，可以一直保持接收客服端的数据
    [sock readDataWithTimeout:-1 tag:0];
    
    // 实现简单聊天室的功能
    //遍历所有的数据交互的socket,进行消息的转发，把客服端的数据发送到其他客户端
    for (GCDAsyncSocket *connectSocket in self.connectSockets) {
        //排除发送者对应的socket
        if (connectSocket != sock) {
            
            [connectSocket writeData:data withTimeout:-1 tag:0];
        }
    }

}


// 懒加载监听的socket
- (GCDAsyncSocket *)listenSocket
{
    if (_listenSocket == nil) {
        _listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0) socketQueue:nil];
    }
    return _listenSocket;
}
- (NSMutableArray<GCDAsyncSocket *> *)connectSockets
{
    if (_connectSockets == nil) {
        _connectSockets = [NSMutableArray array];
    }
    return _connectSockets;
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end
